package com.mxt.moviedemo.service.impl;

import com.mxt.moviedemo.dao.MoviesMapper;
import com.mxt.moviedemo.entity.*;
import com.mxt.moviedemo.service.MoviesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MoviesServiceImpl implements MoviesService {
    @Autowired
    private MoviesMapper moviesMapper;

    @Override
    public PageResult<Movies> getMoviesByPage(PageRequest pageRequest) {
        List<Movies> movies = moviesMapper.getMoviesByPage(pageRequest);
        // 过滤掉null元素
        List<Movies> nonNullMovies = new ArrayList<>();
        for (Movies movie : movies) {
            if (movie != null) {
                nonNullMovies.add(movie);
            }
        }
        int total = moviesMapper.getTotalMovies();
        return new PageResult<>(pageRequest.getPage(), pageRequest.getSize(), total, nonNullMovies);
    }

    @Override
    public PageResult<Movies> searchMoviesByKeyword(PageRequest pageRequest, String keyword) {
        List<Movies> movies = moviesMapper.searchMoviesByKeyword(pageRequest, keyword);
        int total = moviesMapper.getTotalMoviesByKeyword(keyword);
        return new PageResult<>(pageRequest.getPage(), pageRequest.getSize(), total, movies);
    }

    @Override
    public Movies getMovieById(int mid) {
        return moviesMapper.getMovieById(mid);
    }

}
